package at.fhooe.stefanirndorfer.labeling;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;

import at.fhooe.stefanirndorfer.logging.Log;
import at.fhooe.stefanirndorfer.quadtree.QuadTreeNode;

public class Region {
	private static int numRegions = 0;

	private String id;
	private float[]color;
	private ArrayList<QuadTreeNode> leafs;
	private Region destRegion;
	
	public Region(){
		id = this.getClass().getSimpleName() + System.nanoTime();
		leafs = new ArrayList<QuadTreeNode>();
		randomizeColor();
		//Log.info(this, "new Region built!");
		destRegion = null;
		numRegions++;
	}
	
	
	private float[] randomizeColor() {
		this.color = new float[3];
		Random rand = new Random();
		for (int i = 0; i < color.length; i++) {
			color[i] = rand.nextFloat();
		}
		return color;
	}


	public void addLeaf(QuadTreeNode p) {
		leafs.add(p);
	}


	public String getId() {
		return id;
	}


	public float[] getColor() {
		return color;
	}


	public ArrayList<QuadTreeNode> getLeafs() {
		return leafs;
	}


	public void moveRegionTo(Region currDestReg) {
		System.out.println("Hallo, i am Region "+id + " and i move to "+currDestReg.id);
		
		//if (leafs.size() > 0) {
			if (destRegion == null) {
				destRegion = currDestReg;

				Iterator<QuadTreeNode> it = leafs.iterator();
				while (it.hasNext()) {
					QuadTreeNode n = it.next();
					n.setLabel(currDestReg);
					currDestReg.addLeaf(n);
					it.remove();
				}
			}else{
				//if(!this.getId().equals(currDestReg.getId())){ // avoid circular moving
				destRegion.moveRegionTo(currDestReg);
				numRegions--;
				Log.info(this, "NumRegioins: " + numRegions);
//				}
//				else{
//					Log.info(this, "merging skipped");
//				}
			}
		//}
		
	}


	public synchronized void removeLeaf(QuadTreeNode toRemove) {
		for(QuadTreeNode n : leafs){
			if(n.getId().equals(toRemove.getId())){
				leafs.remove(n);
				System.out.println("Region: removed a leaf");
				break;
			}
		}
		
	}


	@Override
	public String toString() {
		String s = "";
		s += "Region: Id: " + id;
		return s;
	}
	
	
	
}
